package com.framework.loippi.utils.qiniu;


import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@Service("qiniuFileServiceImpl")
public class FileServiceImpl implements FileService {

    private Logger log = Logger.getLogger(getClass());
    public static final String uploadImageExtension = "jpg,jpeg,bmp,gif,png";
    public static final String uploadFlashExtension = "swf,flv";
    public static final String uploadMediaExtension = "swf,flv,mp3,wav,avi,rm,rmvb";
    public static final String uploadFileExtension = "zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx";
    /**
     * 分隔符
     */
    private static final String SEPARATOR = ",";

    /**
     * 文件类型
     */
    public enum FileType {

        /**
         * 图片
         */
        image,

        /**
         * Flash
         */
        flash,

        /**
         * 媒体
         */
        media,

        /**
         * 文件
         */
        file
    }

    @Value("${qiniu.region}")
    private String region;
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.url}")
    private String domainUrl;
    @Value("${qiniu.bucket}")
    private String bucket;


    @Resource()
    private TaskExecutor taskExecutor;

    @Override
    public String upload(MultipartFile multipartFile, boolean async) {
        try {
            Configuration config = new Configuration();
            UploadManager uploadManager = new UploadManager(config);
            Auth auth = Auth.create(accessKey, secretKey);
            String filename = UUID.randomUUID().toString().concat("." + FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
            if (async) {
                addTask(multipartFile, filename);
            } else {
                uploadManager.put(multipartFile.getBytes(), filename, auth.uploadToken(bucket));
            }
            return domainUrl.concat(filename);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            log.error(r.toString());
            try {
                // 响应的文本信息
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String upload(String url) {
        try {
            Configuration config = new Configuration();
            UploadManager uploadManager = new UploadManager(config);
            Auth auth = Auth.create(accessKey, secretKey);

            String filename = UUID.randomUUID().toString();
            uploadManager.put(url, filename, auth.uploadToken(bucket));
            return domainUrl.concat(filename);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            log.error(r.toString());
            try {
                // 响应的文本信息
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 添加上传任务
     */
    private void addTask(final MultipartFile multipartFile, final String filename) {
        taskExecutor.execute(new Runnable() {
            public void run() {
                try {
                    Configuration config = new Configuration();
                    UploadManager uploadManager = new UploadManager(config);
                    Auth auth = Auth.create(accessKey, secretKey);
                    uploadManager.put(multipartFile.getBytes(), filename, auth.uploadToken(bucket));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 获取允许上传图片扩展名
     *
     * @return 允许上传图片扩展名
     */
    public String[] getUploadImageExtensions() {
        return StringUtils.split(uploadImageExtension, SEPARATOR);
    }

    /**
     * 获取允许上传Flash扩展名
     *
     * @return 允许上传Flash扩展名
     */
    public String[] getUploadFlashExtensions() {
        return StringUtils.split(uploadFlashExtension, SEPARATOR);
    }

    /**
     * 获取允许上传媒体扩展名
     *
     * @return 允许上传媒体扩展名
     */
    public String[] getUploadMediaExtensions() {
        return StringUtils.split(uploadMediaExtension, SEPARATOR);
    }

    /**
     * 获取允许上传文件扩展名
     *
     * @return 允许上传文件扩展名
     */
    public String[] getUploadFileExtensions() {
        return StringUtils.split(uploadFileExtension, SEPARATOR);
    }


    public final String getToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String token = auth.uploadToken(bucket);
        return token;
    }

    public static void main(String[] args) throws QiniuException {
    }
}
